<template>
  <!--    添加页面-->
  <el-dialog :close-on-click-modal='false' v-drag :title="$t('添加')" append-to-body :v-if="dialogVisible" :visible.sync="dialogVisible" @close="close" top="10vh" width="530px">
    <div class="dialogContentBox">
      <el-form :model="form" :rules="rules" :inline="true" :hide-required-asterisk="true" ref="form" label-position="left" style="margin:0 20px;">
        <el-form-item :label="$t('对象名称')" :label-width="formLabelWidth" prop="name">
          <el-input v-emoji size='small' v-model="form.name" autocomplete="off" style="width:215px;" ref="formName"></el-input>
        </el-form-item>
        <el-form-item :label="$t('类型')" prop="ip_type" :label-width="formLabelWidth">
          <el-select size='small' v-model="form.ip_type" @change="ipTypeChange" clearable :placeholder="$t('请选择')">
            <el-option v-for="item in ipTypeList" :key="item.value" :label="item.lable" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!--IPV4-->
        <div v-if="form.ip_type === 'ipv4'">
          <el-form-item :label="$t('IP地址')" prop="add_ip_str" :label-width="formLabelWidth">
            <el-input v-emoji size='small' v-model="form.add_ip_str" style="width:215px;" ref="addIp"></el-input>
            <el-button type="success" icon="el-icon-plus" circle @click="add_ip(form.add_ip_str)" size="mini" style="margin-left:10px;" class="addIp"></el-button>
          </el-form-item>

          <el-table size='mini' :data="form.ip_array" border style="width: 100%" max-height="400px">
            <el-table-column prop='ip' :label="$t('IP地址')" align="center">
              <template slot-scope="scope">
                <tooltip :copyText="scope.row.ip" class="wid190">
                </tooltip>
              </template>
            </el-table-column>
            <el-table-column fixed="right" :label="$t('操作')" width="120" align="center">
              <template slot-scope="scope">
                <el-button @click.native.prevent="deleteRow(scope.$index, form.ip_array)" type="danger" plain size="mini" :class="'del' +(scope.$index+1)">
                  {{$t('删除')}}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!--IPV4-NET-->
        <div v-if="form.ip_type === 'ipv4-net'">
          <el-form-item :label="$t('网络地址')" prop="ipAddress" :label-width="formLabelWidth">
            <el-input v-emoji size='small' v-model="form.ipAddress" style="width:215px;" ref="ipAddress"></el-input>
          </el-form-item>
          <el-form-item :label="$t('子网掩码')" prop="mask" :label-width="formLabelWidth">
            <el-input v-emoji size='small' v-model="form.mask" style="width:215px;" ref="mask"></el-input>
          </el-form-item>
        </div>
        <!--IPV4-RANGE-->
        <div v-if="form.ip_type === 'ipv4-range'">
          <el-form-item :label="$t('地址范围')" prop="ipStart" style="margin-right:0" :label-width="formLabelWidth">
            <el-input v-emoji v-model="form.ipStart" style="width:117px" size='small' ref="ipStart"></el-input>
          </el-form-item>
          <el-form-item label="" style="margin-right:0">~</el-form-item>
          <el-form-item label-width="0" prop="ipEnd">
            <el-input v-emoji v-model="form.ipEnd" style="width:117px" size='small' ref="ipEnd"></el-input>
          </el-form-item>
        </div>
        <!--IPV6-->
        <div v-if="form.ip_type === 'ipv6'">
          <el-form-item :label="$t('IP地址')" prop="add_ip_str" :label-width="formLabelWidth">
            <el-input v-emoji size='small' v-model="form.add_ip_str" style="width:215px;" ref="addIp"></el-input>
            <el-button type="success" icon="el-icon-plus" circle @click="add_ipv6(form.add_ip_str)" size="mini" style="margin-left:10px;"></el-button>
          </el-form-item>

          <el-table size='mini' :data="form.ipv6_array" border style="width: 100%" max-height="400px">
            <el-table-column prop='ip' :label="$t('IP地址')" align="center">
              <template slot-scope="scope">
                <tooltip :copyText="scope.row.ip" class="wid190">
                </tooltip>
              </template>
            </el-table-column>
            <el-table-column fixed="right" :label="$t('操作')" width="120" align="center">
              <template slot-scope="scope">
                <el-button @click.native.prevent="deleteRow(scope.$index, form.ipv6_array)" type="danger" plain size="mini" :class="'DEL' + (scope.$index + 1)">
                  {{$t('删除')}}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!--IPV6-NET-->
        <div v-if="form.ip_type === 'ipv6-net'">
          <el-form-item :label="$t('网络地址')" prop="ipAddress" :label-width="formLabelWidth">
            <el-input v-emoji size='small' v-model="form.ipAddress" :placeholder="$t('示例：2009::0')" style="width:215px;" ref="ipAddress"></el-input>
          </el-form-item>
          <el-form-item :label="$t('前缀长度')" prop="mask" :label-width="formLabelWidth">
            <el-input v-emoji size='small' v-model="form.mask" :placeholder="$t('示例：64')" type="number" style="width:215px;" ref="formMask"></el-input>
          </el-form-item>
        </div>
        <div v-if="form.ip_type === '6'"></div>
        <!--MAC-->
        <div v-if="form.ip_type === 'mac'">
          <el-form-item :label="$t('MAC地址')" prop="mac" :label-width="formLabelWidth">
            <el-input v-emoji size='small' v-model="form.mac" style="width:215px;" @change="add_mac(form.mac)" ref="mac"></el-input>
          </el-form-item>
        </div>

      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit(form)" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addAddrInfo } from '@/api/list/addr'
import { inputClass } from '@/utils/input-class.js'
export default {
  name: 'ListTools',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入对象名称')))
      } else {
        callback()
      }
    }
    var validateAddIpStr = (rule, value, callback) => {
      let flag = false
      if (this.form.ip_type === 'ipv6') { // ipv6_array
        for (let item of this.form.ipv6_array) {
          if (item.ip === value) {
            flag = true
          }
        }
      }
      if (this.form.ip_type === 'ipv4') {
        for (let item of this.form.ip_array) {
          if (item.ip === value) {
            flag = true
          }
        }
      }
      if (flag) {
        callback(new Error(this.$t('已填加过相同的IP地址')))
      } else if (value === '') {
        callback()
      } else if (this.form.ip_type === 'ipv4' && !this.isValidIP(value)) {
        callback(new Error(this.$t('请输入正确的IP地址')))
      } else if (this.form.ip_type === 'ipv6' && !this.isValidIPv6(value)) {
        callback(new Error(this.$t('请输入正确的IP地址')))
      } else {
        callback()
      }
    }
    var validateIpAddress = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入IP地址')))
      } else if (this.form.ip_type === 'ipv4-net' && !this.isValidIP(value)) {
        callback(new Error(this.$t('请输入正确的IP地址')))
      } else if (this.form.ip_type === 'ipv6-net' && !this.isValidIPv6(value)) {
        callback(new Error(this.$t('请输入正确的IP地址')))
      } else {
        callback()
      }
    }
    var validateMask = (rule, value, callback) => {
      if (this.form.ip_type === 'ipv4-net') {
        if (String(value).trim() === '') {
          callback(new Error(this.$t('请输入子网掩码')))
        } else if (!this.isValidMask(value)) {
          callback(new Error(this.$t('请输入正确的子网掩码')))
        } else {
          callback()
        }
      } else {
        if (!String(value).trim()) {
          callback(new Error(this.$t('请输入前缀长度')))
        } else if (Number(value) < 0 || Number(value) > 128) {
          callback(new Error(this.$t('前缀长度的范围是0-128')))
        } else {
          callback()
        }
      }
    }
    var validateIp = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('请输入IP地址')))
      } else if (!this.isValidIP(value)) {
        callback(new Error(this.$t('请输入正确的IP地址')))
      } else {
        callback()
      }
    }
    var validateMac = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('请输入MAC地址')))
      } else if (!this.isValidMAC(value)) {
        callback(new Error(this.$t('请输入正确的MAC地址')))
      } else {
        callback()
      }
    }
    var validateIpType = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('请选择类型')))
      } else {
        callback()
      }
    }
    return {
      form: {
        id: null,
        old_name: '',
        name: '',
        ip_type: '',
        ip: '',
        ipAddress: '',
        mask: '',
        ipStart: '',
        ipEnd: '',
        mac: '',
        add_ip_str: '',
        ip_array: [],
        ipv6_array: []
      },
      record: {
        id: null,
        old_name: '',
        name: '',
        ip_type: '',
        ip: '',
        ipAddress: '',
        mask: '',
        ipStart: '',
        ipEnd: '',
        mac: '',
        add_ip_str: '',
        ip_array: [],
        ipv6_array: []
      },
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        mask: [{ required: true, validator: validateMask, trigger: 'blur' }],
        add_ip_str: [{ required: true, validator: validateAddIpStr, trigger: 'blur' }],
        ipAddress: [{ required: true, validator: validateIpAddress, trigger: 'blur' }],
        ipStart: [{ required: true, validator: validateIp, trigger: 'blur' }],
        ipEnd: [{ required: true, validator: validateIp, trigger: 'blur' }],
        mac: [{ required: true, validator: validateMac, trigger: 'blur' }],
        ip_type: [{ required: true, validator: validateIpType, trigger: 'change' }]
      },
      ipTypeList: {
        1: { lable: 'IPv4', value: 'ipv4' },
        2: { lable: 'IPv4-NET', value: 'ipv4-net' },
        3: { lable: 'IPv4-RANGE', value: 'ipv4-range' },
        4: { lable: 'IPv6', value: 'ipv6' },
        5: { lable: 'IPv6-NET', value: 'ipv6-net' },
        7: { lable: 'MAC', value: 'mac' }
      },
      ipTypeChangeList: {
        'ipv4': 'ipv4',
        'ipv4-net': 'ipv4',
        'ipv4-range': 'ipv4',
        'ipv6': 'ipv6',
        'ipv6-net': 'ipv6',
        'mac': 'mac'
      },
      formLabelWidth: '110px',
      dialogVisible: false
      // visible: false,
    }
  },
  methods: {
    init () {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['formName', 'addIp', 'ipAddress', 'mask', 'ipStart', 'ipEnd', 'addIp', 'ipAddress', 'formMask', 'mac']
        inputClass(this.$refs, data)
      })
    },
    submit (formName) {
      let validateList = []
      this.$refs['form'].validateField(['name', 'mask', 'ipAddress', 'ipStart', 'ipEnd', 'mac', 'ip_type'], Error => {
        validateList.push(Error)
      })
      if (validateList.every((item) => item === '')) {
        // 咱们的操作
        let formData = JSON.parse(JSON.stringify(formName))
        switch (formName.ip_type) {
          case 'ipv4':
            if (!formData.ip_array || formData.ip_array.length === 0) {
              this.$messages.error(this.$t('请添加ip地址'))
              return
            } else {
              formData.ip = ''
              formName.ip_array.forEach((item, index, array) => {
                if (index < array.length - 1) {
                  formData.ip += item.ip + ','
                } else {
                  formData.ip += item.ip
                }
              })
            }
            break
          case 'ipv6':
            if (!formName.ipv6_array || formName.ipv6_array.length === 0) {
              this.$messages.error(this.$t('请添加ip地址'))
              return
            } else {
              formData.ip = ''
              formName.ipv6_array.forEach((item, index, array) => {
                if (index < array.length - 1) {
                  formData.ip += item.ip + ','
                } else {
                  formData.ip += item.ip
                }
              })
            }
            break
        }
        addAddrInfo(formData).then(response => {
          if (response.status === 0) {
            this.$messages.success(this.$t('添加成功'))
            this.$emit('addrArrayTools', formData.name, this.ipTypeChangeList[formData.ip_type])
            this.close()
          }
        })
      }
    },
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    // 验证ipv4
    isValidIP (ip) {
      let reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
      return reg.test(ip)
    },
    // 验证子网掩码
    isValidMask (mask) {
      let reg = /^(254|252|248|240|224|192|128|0)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(255|254|252|248|240|224|192|128|0)$/
      return reg.test(mask)
    },
    // 验证ipv6
    isValidIPv6 (ip) {
      let reg = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]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-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4}){0,4}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))(%.+)?\s*$/
      return reg.test(ip)
    },
    // 验证MAC地址
    isValidMAC (mac) {
      let reg = /(([A-Fa-f0-9]{2}-){5}[A-Fa-f0-9]{2})|(([A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2})/
      return reg.test(mac)
    },
    add_ip (data) {
      this.$refs['form'].validateField('add_ip_str', Error => {
        if (!Error && data) {
          this.form.ip_array.push({ ip: data })
          this.form.add_ip_str = ''
        }
        if (data === '') {
          this.$messages.error('请填写IP')
        }
      })
    },
    add_ipv6 (data) {
      this.$refs['form'].validateField('add_ip_str', Error => {
        if (!Error && data) {
          this.form.ipv6_array.push({ ip: data })
          this.form.add_ip_str = ''
        }
        if (data === '') {
          this.$messages.error('请填写IP')
        }
      })
    },
    close () {
      this.dialogVisible = false
      this.clearForm()
      this.add_ip_str = ''
      this.$refs.form.resetFields()
    },
    clearForm () {
      this.form = {
        id: null,
        old_name: '',
        name: '',
        ip_type: '',
        ip: '',
        ipAddress: '',
        mask: '',
        ipStart: '',
        ipEnd: '',
        mac: '',
        add_ip_str: '',
        ip_array: [],
        ipv6_array: []
      }
      this.record = {
        id: null,
        old_name: '',
        name: '',
        ip_type: '',
        ip: '',
        ipAddress: '',
        mask: '',
        ipStart: '',
        ipEnd: '',
        mac: '',
        add_ip_str: '',
        ip_array: [],
        ipv6_array: []
      }
    },
    ipTypeChange () {
      this.form.ipAddress = ''
      this.form.mask = ''
      this.form.ipStart = ''
      this.form.ipEnd = ''
      this.form.mac = ''
      this.form.add_ip_str = ''
      this.form.ip_array = []
      this.form.ipv6_array = []
      this.$refs.form.clearValidate()
    }
  }
}
</script>

<style scoped>
.circle {
  padding: 5px;
}

.dialogContentBox {
  max-height: calc(100vh - 224px);
  overflow-y: auto;
}
</style>
